package com.demo.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.demo.dto.Result;
import com.demo.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.demo.utils.SystemConstants.IMAGE_UPLOAD_DIR;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    /**
     * 帖子上传图片
     * @param file
     * @return
     */
    @PostMapping("bolg")
    public Result uploadImage(@Param("file") MultipartFile file){
        try {
        //获取文件的名称
        String fileName = file.getOriginalFilename();
        //生成新的文件名
        String newFileName = createNewFileName(fileName);
           //保存文件
            file.transferTo(new File(IMAGE_UPLOAD_DIR,newFileName));
            log.debug("文件上传成功",newFileName);
            return Result.ok(newFileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败",e);
        }
    }

    /**
     * 存储的文件路径
     * @param originalFilename
     * @return
     */
    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = java.util.UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File(SystemConstants.IMAGE_UPLOAD_DIR, StrUtil.format("/blogs/{}/{}", d1, d2));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/blogs/{}/{}/{}.{}", d1, d2, name, suffix);
    }
}
